﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using DotNetStar.TheKing.Infrastructure;
using DotNetStar.TheKing.Models;
using DotNetStar.TheKing.Services;
using DotNetStar.TheKing.Web.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;

namespace DotNetStar.TheKing.Web.Pages.Content
{
    public class EditModel : PageModel
    {
        public int AttachBatchId { get; set; } = new Random(DateTime.Now.Millisecond).Next(100_000, 999_999);

        private readonly ContentService _contentService;
        private readonly IHostingEnvironment _environment;
        private readonly ILogger<EditModel> _logger;
        public EditModel(ContentService contentService, IHostingEnvironment environment,ILoggerFactory loggerFactory)
        {
            _contentService = contentService;
            _environment = environment;
            _logger = loggerFactory.CreateLogger<EditModel>();
        }

        public async Task<IActionResult> OnGetContentAsync(int? id,Channels channel= Channels.Content)
        {
            _logger.LogDebug("当前频道：{0}", channel);

            var model = new EditContentViewModel
            {
                Channel = channel
            };


            if (id.HasValue && id.Value>0)
            {
                var content = await _contentService.GetContentAsync(id.Value,false);
                if (content == null)
                {
                    return NotFound();
                }

                if(content.IsAsk && content.IsLockComment)
                {
                    return Unauthorized();
                }

                if (content.Author.Id != User.Identity.UserId())
                {
                    return Unauthorized();
                }
                model.Channel = content.Channel;
                model.Tags = content.GetTagNames();
                model.Id = id.Value;
                model.Subject = content.Subject;
                model.Body = content.Body;
                model.IsOriginal = content.IsOriginal;
                model.Cost = content.Cost;
                // this.Tags = content.Tags.Select(m => m.TagName);
                model.OrderNo = content.OrderNo;
                model.CategoryId = content.CategoryId;
                model.IsDraft = content.Status== ContentStatus.Draft;
                model.IsSecret = content.IsSecret;
                model.Url = content.Url;
                model.InvitedUsers = content.InvitedUsers;
            }
            else
            {
                using (StreamReader reader = new StreamReader($"{_environment.WebRootPath}/markdown-example.md"))
                {
                    model.Body = reader.ReadToEnd();
                }
                model.IsOriginal = true;


                if (model.IsAsk)
                {
                    model.Cost = 1;//最小悬赏值
                }
            }


            return StatusCode(200,model);
        }

        public async Task<IActionResult> OnGetCategoryAsync(int pid)
        {
            var categoryList = await _contentService.GetCategoriesByParentAsync(pid);
            return StatusCode(200, categoryList);
        }

        public async Task<IActionResult> OnPostAsync(EditContentViewModel model)
        {
            if (!model.IsValid())
            {
                return StatusCode(400, model.GetErrors().Join(";"));
            }

            try
            {
                var result = await _contentService.SaveContentAsync(model, User.Identity.UserId());


                if (result.IsSucceed)
                {
                    if (model.Cost.HasValue)
                    {
                        await HttpContext.RefreshAsync(User.Identity.UserId());
                    }

                    return StatusCode(200, Url.Page("./Success", new { id = result.Data.Id }));
                }
                var errors = result.Errors.Aggregate((prev, next) => $"{prev}；{next}");

                _logger.LogDebug("保存帖子的结果：{0}，原因：", result.IsSucceed, errors);
                return StatusCode(400, errors);
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }
        
    }
}